angular.module('orderDetail', []).controller('orderDetailCtrl', [
    '$scope',
    'httpService',
    '$stateParams',
    '$timeout',
    'alertmsg',
    '$state',
    '$localStorage',
    '$rootScope',
    'confirmservice',
    '$interval',
    '$sce',
    function($scope, httpService, $stateParams, $timeout, alertmsg, $state, $localStorage, $rootScope, confirmservice, $interval, $sce) {
        // 获取参数id
        var id = $stateParams.id
        $scope.nowToken = $localStorage.mutian_token;
        $scope.setisinstalltime=true;
        $scope.alert=false;

        // 获取状态数组
        $scope.statesArrs = angular.copy(statesArrs);
        var newstatesArrs = angular.copy(statesArrs);
        // 默认为新订单
        $scope.arrindex = 0;

        function setArrStateIndex(data) {
            // 判断是否是安装单
            if (data.mount_order) {
                $scope.statesArrs.splice(1, 2);
                newstatesArrs.splice(1, 2);
            }
            angular.forEach(newstatesArrs, function(v, k) {
                if (v.state.split(',').indexOf(data.workflow_state) != -1) {
                    $scope.arrindex = k;
                }
            });
        }

        $scope.updateState = setArrStateIndex;

        // 时间选择
        var time = new Date().getTime();
        var opts = {
            minDate: new Date(),
            enableTime: true,
            dateFormat: 'Y-m-d H:i',
            mode: 'single',
            locale: 'zh',
            onChange: function(selectedDates, dateStr, instance) {
                var selectTime = new Date(selectedDates[0]).getTime() / 1000;
                if ('changeflatpickr' == instance.element.id) {
                    if ($scope.order.mount_order) {
                        $scope.order.install_date = selectTime;
                    } else {
                        $scope.order.booking_date = selectTime;
                    }
                } else if (instance.element.id == 'flatpickrc') {
                    $scope.order.install_date = selectTime;
                }
            }
        };
        $.getScript('./lib/flatpickr/dist/l10n/zh.js', function() {
            flatpickr("#changeflatpickr", opts);
            opts.minDate = new Date($stateParams.time * 1000);
            $timeout(function() {
                flatpickr("#flatpickrc", opts);
            }, 500)
        });


        // 跳转到地图订单
        $scope.goMap = function(role, id) {
            if (role == 2) {
                $state.go('mine.changeorder', { id: order.id });
            }
        };

        // 获取订单
        // 参数 id
        $scope.order;
        $scope.isFirstUpload;
        $scope.getOrderById = function() {
            httpService.query('web/orders/' + id).then(function(res) {
                if (res.code == 200) {
                    $scope.order = res.order;
                    console.log($scope.order);
//                  if($scope.order.install_date!=null || $scope.order.install_date!=''){
//                  		$scope.setisinstalltime=false
//                  }else{
//                  		$scope.setisinstalltime=true
//                  }
                    getFetch();
                    if($scope.order.completed_pictures.length!=0){
                    		window.localStorage.removeItem("pig");
                    }
                    $scope.pig=angular.fromJson(window.localStorage.getItem("pig"));
        				console.log($scope.pig)
                    if (res.order.measure_pictures.length == 0) {
                        $scope.isFirstUpload = false;
                    } else {
                        $scope.isFirstUpload = true;
                    }
                    $scope.editOrder = res.order;
                    setArrStateIndex(res.order);
                }
            });
        }
        $scope.getOrderById();

        // 更新订单  bool: 表单验证是否通过，order:订单，ismaster
        $scope.putOrderDetail = function(bool, order, isUpdateMaster) {
            $scope.ismodalorderform1 = false; // 编辑弹出框 判断是否点击了提交
            if (!bool) {
                var obj = {
                    id: order.id,
                    name: order.name,
                    tel: order.tel,
                    facilitator_id: order.facilitator_id
                };
                if (order.booking_date) {
                    obj.booking_date = order.booking_date;
                }
                if (order.install_date) {
                    obj.install_date = order.install_date;
                }
        
                console.log(obj)
//              httpService.query('web/orders/' + order.id, obj, 'put').then(function(res) {
//                  $('#myModal').modal('hide');
//                  if (res.code == 200) {
//                  		$scope.setisinstalltime = false;
//                      // if (ismaster && oldorder && oldorder.facilitator_id != $scope.order.facilitator_id) {
//                      //     window.history.go(-1);
//                      // }
//                      if (isUpdateMaster) {
//                          alertmsg('订单成功指派给' + $scope.order.service_info.name + '了！');
//                      }
//                      $scope.order = res.order;
//                      $('#speedimg1').ready(function(e) {
//                          loadDefaultPic(e, '#speedimg1', '#previewul1', 9);
//                      });
//                  } else {
//                      alert(res.msg);
//                  }
//              });
            } else {
                $scope.ismodalorderform1 = true;
            }
        };

        // 取消订单
        $scope.deleteOrder = function(id, index) {
            confirmservice('是否取消？').then(function(bool) {
                if (bool) {
                    httpService.query('web/orders/' + id, '', 'delete').then(function(res) {
                        if (res.code == 200) {
                            $scope.order = res.order;
                            alertmsg('取消订单成功！');
                        } else {
                            alertmsg(res.msg);
                        }
                    });
                }
            });
        };

        // 服务商修改订单
        $scope.changeOrder = function(order) {
            $state.go('mine.changeorder', { id: order.id });
        };

        // 加载默认图片
        var defaultpic = './components/mine/orders/orderdetail/imgs/add.png';

        function loadDefaultPic(e, parent, child, num) {
            $scope.loadDefaultPics = [];
            pics = [];
            var previewul = $(child);
            previewul.off('click', 'li');
            previewul.find('li').remove();
            if (!num) {
                num = 6;
            }
            for (var i = 0; i < num; i++) {
                $scope.loadDefaultPics.push(defaultpic);
                pics.push(false);
                var html = '<li><img id="previewid' + i + '" data-index="' + i + '" src="' + defaultpic + '" /></li>'
                $(child).append(html);
            }
            changePic(e, parent, child, num);
        }

        // 渲染图片
        function rendererPic(child, i, defaultpic) {
            var html = '<li><img id="previewid' + i + '" data-index="' + i + '" src="' + defaultpic + '" /></li>'
            $(function() {
                $(child).append(html);
            });
        }

        // 更改图片
        function changePic(e, parent, child, num) {
            var previewul = $(child);
            previewul.on('click', 'li', function(e, b, c) {
                changeindex = e.target.id.split('previewid')[1];
                speedimgid = parent + changeindex;
                var img = $(child).find('li').eq(changeindex).find('img')[0];
                $(speedimgid).click();
                $(speedimgid).change(function(ec) {
                    onefiles = ec.target.files || ec.dataTransfer.files;
                    var fReader = new FileReader();
                    fReader.readAsDataURL(onefiles[0]);
                    fReader.onloadend = function(event) {
                        pics[changeindex] = true;
                        img.src = event.target.result;
                    }
                });
            });
        }

        // 预览图片
        var pics = [];
        $scope.$watch('order.workflow_state', function(newData, oldData) {
            if (['appointed_measurement', 'measured'].indexOf(newData) != -1) {
                $('#speedimg').ready(function(e) {
                    loadDefaultPic(e, '#speedimg', '#previewul', 6);
                });
            } else if (newData == 'appointed_installation') {
                $('#speedimg1').ready(function(e) {
                    loadDefaultPic(e, '#speedimg1', '#previewul1', 9);
                });
            }
        });

        // 上传图纸
        $scope.firstImgUpload = true;
        $scope.completed = function(type, imgtype, element_id) {
            if ($scope.firstImgUpload) {
                $scope.firstImgUpload = false;
                var f = new FormData();
               
                angular.forEach(pics, function(v, k) {
                    if (v) {
                        var file = document.getElementById(element_id + k).files[0];
                        f.append('pictures[][image]', file);
                        f.append('pictures[][image_type]', imgtype);
                    }
                });
                 console.log(f)
                $timeout(function() {
                    httpService.query('web/orders/' + id + '/upload_data', f, 'post', true).then(function(res) {
                        $scope.firstImgUpload = true;
                        if (res.code == 200) {
                            $('#speedimg').ready(function(e) {
                                loadDefaultPic(e, '#speedimg', '#previewul', 6);
                            });
                            $scope.order = res.order;
                            setArrStateIndex(res.order);
                        } else {
                            alertmsg(res.msg);
                        }
                    }, function() {
                        $scope.firstImgUpload = true;
                    });
                }, 500);
            } else {
                alertmsg('上传中请稍等！');
            }
        };

        // 下载pdf
        $scope.downloadPdf = function(url) {
            var split_url = url.slice(-3);
            if (['pdf', 'dwg'].indexOf(split_url) != -1) {
                window.open($sce.trustAsUrl(url), '_blank');
            }
        };

        $scope.closeModal = function() {
            $('#myModal').modal('hide');
        };

        // 上传文件信息
        $scope.uploadFile = function() {
            // console.log($('#xml-file'))
            // console.log($("#xml-file")[0].files[0])
            var file = $("#xml-file")[0].files[0]
            var f = new FormData()
            if (file) {
                f.append('pictures[][image]', file)
                f.append('pictures[][image_type]', 'xml')
                httpService.query('web/orders/' + id + '/upload_data', f, 'post', true).then(function(res) {
                    // console.log(res)
                })
            }
        };

        // 选择安装时间
        $scope.installTime = function() {
            if ($scope.order && $scope.order.install_date) {
                httpService.query('web/orders/' + id + '/installed_form', {
                    install_date: $scope.order.install_date
                }, 'post').then(function(res) {
                    if (res.code == 200) {
                        // $scope.changeInstallTime = false;
                        setArrStateIndex(res.order);
                        $scope.order = res.order;
                        alertmsg('预约安装时间成功');
                    } else {
                        alertmsg(res.msg);
                    }
                })
            } else {
                alertmsg('请选择预约安装时间!');
            }
        };

        // 确认安装
        $scope.installed = function() {
            confirmservice('是否确认安装完成？').then(function(bool) {
                if (bool) {
                    httpService.query('web/orders/' + id + '/state_event', {}, 'post').then(function(res) {
                        if (res.code == 200) {
                            setArrStateIndex(res.order);
                            $scope.order = res.order;
                            alertmsg('安装完成！');
                        } else {
                            alertmsg(res.msg);
                        }
                    });
                }
            });
        };

        // 更新时间或师傅
        $scope.updateTimeAndMaster = function(bool, order, self) {
        		console.log()
            var obj = {
                id: $scope.order.id,
                facilitator_id: $scope.order.facilitator_id
            };
            if ($scope.order.install_date && $scope.order.service_info.name) {
            		console.log("ddd");
            		 obj.install_date = $scope.order.install_date;
            		$scope.putOrderDetail(false, obj, self);
            } else {
            		if(!$scope.order.install_dat){
            			alertmsg('请选择预约安装时间！');
            		}
            		if(!$scope.order.service_info.name){
            			alertmsg('请选择预约安装师傅！');
            		}
//              if (!self) {
//                  alertmsg('请选择预约安装时间！');
//                  return
//              }
//              $scope.putOrderDetail(false, obj, self);
            }
            if(user.id==$scope.order.facilitator_id){
            		window.localStorage.setItem("pig", JSON.stringify(true));
            }
        };
        // 评分
        $scope.comment = [{
            title: 'measure',
            raty: 5,
            content: '服务很好，会推荐给朋友！'
        },{
            title: 'installed',
            raty: 5,
            content: '服务很好，会推荐给朋友！'
        }];
        $scope.arrs = [1, 2, 3, 4, 5];
        $scope.commentOrder = function(comment) {
            // console.log('comment', comment);
            $scope.comment[0].user_id = $scope.order.customer_service_id;
            $scope.comment[1].user_id = $scope.order.facilitator_id;
            httpService.query('web/orders/' + id + '/comments', { comments: comment }, 'post').then(function(res) {
                if (res.code == 200) {
                    setArrStateIndex(res.order);
                    $scope.order = res.order;
                    if( res.order.is_comment && res.order.measure_comment && !user.company_id ) {
                        $('#payModal').modal('show');
                    }
                    if (res.order.comment) {
                        $scope.comment.raty = res.order.comment.raty;
                        $scope.comment.content = res.order.comment.content;
                    }
                    $scope.getOrderById();
                } else {
                    alertmsg(res.msg);
                }
            });
        };
        
        // 设置评分
        $scope.setRaty = function(raty, state, idx) {
            // console.log('raty, state, idx', raty, state, idx)
            if (['installed', 'confirm_installed'].indexOf(state) != -1) {
                $scope.comment[idx].raty = raty;
            }
        };


        function getPersion() {
            if ($localStorage.user && $localStorage.user.id) {
                httpService.query('web/users/' + $localStorage.user.id).then(function(res) {
                    if (res.code == 200) {
                        $localStorage.user = $rootScope.user = res.user;
                        console.log($localStorage.user);
                    }
                });
            }

        };
        getPersion();

        // 用户支付订单
        $scope.payOrder = function() {
            if (!isMobile) {
                pay_type = 'alipay_pc_direct';
            }
            httpService.query('web/orders/' + id + '/payment', {
                pay_type: pay_type
            }, 'post').then(function(res) {
                $('#payModal').modal('hide');
                if (res.code == 200) {
                    getPersion();
                    setArrStateIndex(res.order);
                    $scope.order = res.order;
                    alertmsg('支付成功!');
                } else {
                    alertmsg(res.msg);
                    if (res.code == 301) {
                        $state.go('mine.recharge', { money: $scope.order.amount_total_count });
                    }
                }
            });
        };

        // 待换方法
        // $scope.$watch('order', function(newData, oldData) {
        //     if (newData) {
        //         newData.total_all = parseFloat(newData.total) + newData.measure_amount;
        //     }
        // });

        //---------------------------新的上传图片的功能------------------------------

        // 初始化单项的循环次数
        function initInputFile(brand_id, num) {
            var input_tag = 'measure_pictures';
            var arr = [];
            for (var i = 0; i < num; i++) {
                arr.push({ id: brand_id + input_tag + i });
            }
            return arr;
        }
        
        function updateImg(brand_id, num) {
            if (!num) { num = 3; }
            loadSelectPic(brand_id);
            var obj = {
                brand_id: brand_id,
                image_type: 'measure_pictures',
                data_group: initInputFile(brand_id, num)
            };
            return obj;
        }
        
        //设置初始化数据
        $scope.uploadDatas = []

        // 默认上传一组图片
        var allnums = 1;
        function getFetch() {
            httpService.query('web/fetch_source').then(function(res) {
                if (res.code == 200) {
                    $scope.fetchs = res;
                    allnums = $scope.fetchs.company.length;
                    if(allnums >= 3) {
                        allnums = 3;
                    }
                    var id = $scope.fetchs.company[0].id;
                    $scope.uploadDatas[0] = updateImg($scope.order.company_id? $scope.order.company_id: id, 3);
                }
            });
        }
        
        // 添加删除项
        $scope.addUploadDatas = function() {
            var idx = $scope.uploadDatas.length;
            if (idx < allnums) {
                var id = $scope.fetchs.company[idx].id;
                $scope.uploadDatas.push(updateImg(id, 3));
            } else {
                alertmsg('最多添加三组图片!');
            }
        };

        $scope.deleteUploadDatas = function(key) {
            $scope.uploadDatas.splice(key, 1);
        };

        // 添加按钮的点击事件
        var clearDatas = [];
        function loadSelectPic(cla) {
            var cla = '.uploadImageBtn' + cla;
            $(document).ready(function() {
                $(cla).on('click', 'img', function(e) {
                    var self = this;
                    clearDatas.push(self);
                    var inputId = '#' + $(this).data('id');
                    var img = $(this);
                    e.preventDefault();
                    e.stopPropagation();
                    $(inputId).click();
                    $(inputId).on('change', function(e) {
                        onefiles = e.target.files || e.dataTransfer.files;
                        var fReader = new FileReader();
                        fReader.readAsDataURL(onefiles[0]);
                        fReader.onloadend = function(event) {
                            self.src = event.target.result;
                        }
                    });
                });
            });
        }

        $scope.firstImgUpload = true;
        $scope.uploadFileNew = function(type, imgtype, element_id) {
            var f = new FormData();
            var clear_datas = []
            angular.forEach($scope.uploadDatas, function(v, k) {
                angular.forEach(v.data_group, function(a, idx) {
                    var inputfile = document.getElementById(a.id);
                    var file = inputfile.files[0];
                    if (file) {
                        clear_datas.push(inputfile);
                        f.append('pictures[][brand_id]', v.brand_id);
                        f.append('pictures[][image]', file);
                        f.append('pictures[][image_type]', 'measure_pictures');
                    }
                });
            });
            if ($scope.firstImgUpload) {
                $scope.firstImgUpload = false;
                httpService.query('web/orders/' + id + '/upload_data', f, 'post', true).then(function(res) {
                    $scope.firstImgUpload = true;
                    if (res.code == 200) {
                        clearDatas.forEach(function(v, k) { v.src = './components/mine/orders/imgs/addpic.png'; });
                        $scope.order = res.order;
                        setArrStateIndex(res.order);
                    } else {
                        alertmsg(res.msg);
                    }
                });
            } else {
                alertmsg('上传中请稍等！');
            }
            
        };

        function showError(msg) {
            $scope.noperson = msg;
            $timeout(function() {
                $scope.noperson = '';
            }, 1500);
        }

        function waitGetMaster() {
            var timer;
            if (timer) {
                $interval.cancel(time);
            }

            timer = $interval(function() {
                $scope.getMaster($scope.keyword);
                $interval.cancel(timer);
            }, 500);
        }

        $scope.$watch('keyword', function(newData, oldData) {
            if(newData) {
                waitGetMaster();
            }
        });

        // 设定师傅
        $scope.setMaster = function(master) {
            oldorder = angular.copy($scope.order);
            $scope.order.facilitator_id = master.id;
            $scope.order.service_info.name = master.real_name;
            $scope.master = master;
            $scope.masters = null;
            $scope.keyword = '';
            $('#servermodal').modal('hide')
        };
                // 搜索安装师傅
        $scope.getMaster = function(keyword) {
            var first = 1;
            $scope.noperson = '';
            if (keyword && first == 1) {
                ++first;
                httpService.query('web/users/fetch_master', { keyword: keyword, page: 1, limit: limit }).then(function(res) {
                    first == 1;
                    if (res.code == 200) {
                        $scope.masters = res.users;
                        $scope.firstImgUpload = true;
                    }
                }, function() {
                    first == 1;
                });
            } else {
                first == 1
                showError('请输入关键字!');
            }
        };
    }
]);
